<?php

namespace app\admin\model\yunfood;

/**
 * 菜品
 */
class Food extends \addons\yunfood\model\Food
{
    // 自定义初始化
    protected static function init()
    {
        self::beforeWrite(function ($record) {
            $scenario = $record->data['scenario'] ?? null;
            if ($scenario) {
                $skuData = json_decode($record->data['skuData'], true);
                if ($record->multi_spec) {
                    $record->market_price = min(collection($skuData)->column('market_price'));
                    $record->price = min(collection($skuData)->column('price'));
                }
            }
        });

        self::afterWrite(function ($record) {
            $scenario = $record->data['scenario'] ?? null;
            if ($scenario) {
                // 处理规格
                $specData = json_decode($record->data['specData'], true);
                if (! $record->multi_spec) {
                    $specData = [];
                }

                // 现有规格
                $existIds = FoodSpec::where(['food_id' => $record->id])->column('id');

                // 新增和更新规格
                $saveIds = [];
                if ($specData) {
                    foreach ($specData as $key => $item) {
                        if (empty($item['id'])) {
                            $foodSpec = new FoodSpec();
                            $foodSpec->scenario = 'batch';
                            $foodSpec->food_id = $record->id;
                        } else {
                            if (! $foodSpec = FoodSpec::get($item['id'])) {
                                continue;
                            }
                            $foodSpec->scenario = 'batch';
                        }
                        $foodSpec['name'] = $item['name'];
                        $foodSpec->items = $item['items'];
                        $foodSpec->weigh = $key;
                        $foodSpec->allowField(true)->save();
                        $saveIds[] = $foodSpec->id;
                    }
                }

                // 删除规格
                if ($existIds) {
                    if ($deleteIds = array_diff($existIds, $saveIds)) {
                        FoodSpec::where('id', 'in', $deleteIds)->delete();
                    }
                }

                // --------------------------

                // 处理SKU
                $skuData = json_decode($record->data['skuData'], true);
                if (! $record->multi_spec) {
                    $skuData = [];
                }

                // 现有SKU
                $existIds = FoodSku::where(['food_id' => $record->id])->column('id');

                // 新增和更新SKU
                $saveIds = [];
                if ($skuData) {
                    foreach ($skuData as $item) {
                        if (empty($item['id'])) {
                            $foodSku = new FoodSku();
                            $foodSku->scenario = 'batch';
                            $foodSku->food_id = $record->id;
                        } else {
                            if (! $foodSku = FoodSku::get($item['id'])) {
                                continue;
                            }
                            $foodSku->scenario = 'batch';
                        }
                        $foodSku->spec_text = $item['spec_text'];
                        $foodSku->spec_data = $item['spec_data'];
                        $foodSku->cover_url = $item['cover_url'];
                        $foodSku->market_price = $item['market_price'];
                        $foodSku->price = $item['price'];
                        $foodSku->count_left = $item['count_left'];
                        $foodSku->status = $item['status'];
                        $foodSku->allowField(true)->save();
                        $saveIds[] = $foodSku->id;
                    }
                }

                // 删除SKU
                if ($existIds) {
                    if ($deleteIds = array_diff($existIds, $saveIds)) {
                        FoodSku::where('id', 'in', $deleteIds)->delete();
                    }
                }

                // 更新库存
                if ($specData) {
                    $skuCountLeft = FoodSku::where(['food_id' => $record->id, 'status' => FoodSku::STATUS_NORMAL])
                        ->sum('count_left');
                    Food::update(['count_left' => $skuCountLeft], ['id' => $record->id]);
                }
            }

            return true;
        });
    }

    // 封面图 - 覆盖父类
    public function getCoverUrlAttr($value, $data)
    {
        return $value;
    }
}
